const fs = require('fs');
const knex = require('knex').default;
const config = require('../config').get();
const logger = require('./logger');
const sqlClient = knex({
  client: config.database.driver,
  version: '5.7',
  connection: {
      host: `${config.database.host}`,
      port: config.database.port,
      user: `${config.database.user}`,
      password: `${config.database.password}`,
      database: `${config.database.database}`
  }
});

async function runSql(path) {
  const script = fs.readFileSync(path).toString();
  logger.info("Going to run a sql file:");
  logger.info(script);
  /**
   * 拆成一句句sql来执行是因为，knex执行一串语句时，会把它们都算进一个事务内
   * 忽略注释
   * 去首尾空格
   * 按冒号分句
   * 校验字串是否为sql语句
   * @type {string[]}
   */
  const sqls = script.replace(/\/\*[\s\S]*?\*\/|(--|\#)[^\r\n]*/gm, '').trim().replaceAll('\r','').split(';').filter(str=>{
      return str.trim() ? true : false;
  });
  for(const sql of sqls){
    await sqlClient.raw(`${sql};`);
  }
}

async function init() {
  if(config.database.init.mode=='always') {
    const schema = runSql(`${config.database.init.schema}`);
    schema
      .then(res=>{
        const data = runSql(`${config.database.init.data}`);
        data
          .then(res=>{
            logger.info("Database inits successfully!")
          }).catch(err=>{
            logger.error(err);
            process.exit(1);
        })
      }).catch(err=>{
        logger.error(err);
        process.exit(1);
    })
  }
};

module.exports = {
  runSql,
  sqlClient,
  init
}
